package tw.asap.plus.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import tw.asap.plus.R;
import tw.asap.plus.entity.SubCartBean;
import tw.asap.plus.entity.response.GoodsDetailNV;
import tw.asap.plus.entity.response.GoodsInfoNV;
import tw.asap.plus.presenter.CartPresenter;
import tw.asap.plus.presenter.CartPresenterImpl;
import tw.asap.plus.ui.activity.GoodsDetailActivity;
import tw.asap.plus.ui.activity.MerchantActivity;
import tw.asap.plus.ui.custom.PinnedSectionListView;
import tw.asap.plus.ui.custom.QuantityController;
import tw.asap.plus.ui.custom.Tag;
import tw.asap.plus.ui.custom.TagView;

/**
 * Description:
 * Created:      [15/11/3]
 * Author:       [Yang]
 **/
public class PinedSectionAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter, AdapterView.OnItemClickListener {

    ArrayList<GoodsItem> mList;
    Context mContext;
    private LayoutInflater mInflater;
    private ArrayList<GoodsItem> categoryList;
    private CategoryAdapter categoryAdapter;
    private CartPresenter presenter;

    public PinedSectionAdapter(Context mContext, ArrayList<GoodsItem> mList) {
        this.mList = mList;
        this.mContext = mContext;
        mInflater = LayoutInflater.from(mContext);
    }

    public void bindCategory(ArrayList<GoodsItem> categoryList, CategoryAdapter categoryAdapter) {
        this.categoryList = categoryList;
        this.categoryAdapter = categoryAdapter;
    }

    @Override
    public boolean isItemViewTypePinned(int viewType) {
        return viewType == GoodsItem.SECTION;
    }

    @Override
    public int getCount() {
        return mList != null ? mList.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (mList.get(position).type == GoodsItem.SECTION) {
            View section = mInflater.inflate(R.layout.list_group_item, null);
            ((TextView) section.findViewById(R.id.group_title)).setText(mList.get(position).text);
            return section;
        } else {
            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_goods, null);
            }
            if (convertView.getTag() == null) {
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            }
            holder = (ViewHolder) convertView.getTag();
            holder.goodsImg.setImageURI(Uri.parse(mList.get(position).itemEntity.getImg()));
            String price = String.format("%d", Integer.parseInt(mList.get(position).itemEntity.getPrice()) / 100);
            holder.price.setText("$ ".concat(price));
            holder.goodsName.setText(mList.get(position).text);
            holder.quantityController.reset();
            holder.model.setText("已售".concat(mList.get(position).itemEntity.getSales_nums()).concat("份"));
            mList.get(position).hasSub = mList.get(position).itemEntity.getProps() != null && mList.get(position).itemEntity.getProps().size() > 0;
            holder.subLayout.removeAllViews();
            if (!mList.get(position).hasSub) {
                holder.quantityController.setStatus(mList.get(position).count);
            } else if (mList.get(position).subList != null && mList.get(position).subList.size() > 0) {
                //fill the child views
                for (SubCartBean bean : mList.get(position).subList) {
                    RelativeLayout subItemView = (RelativeLayout) mInflater.inflate(R.layout.item_subgoods, null);
                    QuantityController controller = (QuantityController) subItemView.findViewById(R.id.quantity_controller);
                    controller.setStatus(bean.getCount());
                    controller.setOnAddListener(new QuantityController.QuantityChangeListener() {
                        @Override
                        public void onChange(int newQuantity) {
                            SubCartBean newBean = new SubCartBean();
                            newBean.setCount(1);
                            newBean.setGoodsId(bean.getGoodsId());
                            newBean.setPropertyMap(bean.getPropertyMap());
                            presenter.addSubItem(newBean, mList.get(position));
                            categoryAdapter.notifyDataSetChanged();
                        }
                    });
                    controller.setOnMinusListener(new QuantityController.QuantityChangeListener() {
                        @Override
                        public void onChange(int newQuantity) {
                            SubCartBean newBean = new SubCartBean();
                            newBean.setCount(1);
                            newBean.setGoodsId(bean.getGoodsId());
                            newBean.setPropertyMap(bean.getPropertyMap());
                            presenter.minusSubItem(newBean, mList.get(position));
                            categoryAdapter.notifyDataSetChanged();
                        }
                    });
                    TagView tagView = (TagView) subItemView.findViewById(R.id.tagView);
                    for (GoodsDetailNV.PropsEntity.ValuesEntity value : bean.getPropertyMap().values()) {
                        Tag tag = new Tag(value.getValue());
                        tag.layoutColor = mContext.getResources().getColor(R.color.asap_green);
                        tag.layoutColorPress = mContext.getResources().getColor(R.color.asap_green);
                        tag.tagTextColor = mContext.getResources().getColor(R.color.white);
                        tag.layoutBorderColor = mContext.getResources().getColor(R.color.palette_gray_light);
                        tag.layoutBorderSize = 1l;
                        tag.radius = 10l;
                        tagView.addTag(tag);
                    }
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    tagView.post(new Runnable() {
                        @Override
                        public void run() {
                            tagView.refreshTag();
                        }
                    });
                    holder.subLayout.addView(subItemView, params);
                }
            }

            holder.quantityController.setOnMinusListener(newQuantity -> {
                if (mList.get(position).hasSub) {
                    Intent intent = new Intent(mContext, GoodsDetailActivity.class);
                    intent.putExtra("GOODS_INFO", mList.get(position));
                    intent.putExtra("SHOP_INFO", ((MerchantActivity) mContext).getShopEntity());
                    intent.putExtras(((MerchantActivity) mContext).getIntent());
                    mContext.startActivity(intent);
                } else if (presenter != null) {
                    ((CartPresenterImpl)presenter).minus(mList.get(position),false);
                    categoryAdapter.notifyDataSetChanged();
                }
            });
            holder.quantityController.setOnAddListener(newQuantity -> {
                if (mList.get(position).hasSub) {
                    Intent intent = new Intent(mContext, GoodsDetailActivity.class);
                    intent.putExtra("GOODS_INFO", mList.get(position));
                    intent.putExtra("SHOP_INFO", ((MerchantActivity) mContext).getShopEntity());
                    intent.putExtras(((MerchantActivity) mContext).getIntent());
                    mContext.startActivity(intent);
                } else if (presenter != null) {
                    ((CartPresenterImpl)presenter).add(mList.get(position),false);
                    categoryAdapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }
    }

    @Override
    public int getItemViewType(int position) {

        return mList != null ? mList.get(position).type : -1;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    public void bindCartView(CartPresenter presenter) {
        this.presenter = presenter;
        presenter.bindGoodsList(mList);
        presenter.bindCategoryList(categoryList);
        presenter.setAdapter(this);
        presenter.setSecondAdapter(categoryAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mList.get(position).type == GoodsItem.ITEM) {
            Intent intent = new Intent(mContext, GoodsDetailActivity.class);
            intent.putExtra("GOODS_INFO", mList.get(position));
            intent.putExtra("SHOP_INFO", ((MerchantActivity) mContext).getShopEntity());
            intent.putExtras(((MerchantActivity) mContext).getIntent());
            mContext.startActivity(intent);
        }
    }


    public static class GoodsItem implements Parcelable {

        public static final int ITEM = 0;
        public static final int SECTION = 1;

        public GoodsInfoNV.ItemListEntity itemEntity;

        public final int type;
        public final String text;
        public int count;

        public int sectionContainCount;
        public boolean isSelect;
        public int sectionPosition;
        public int listPosition;
        public boolean hasSub;
        public List<SubCartBean> subList;

        public GoodsItem(int type, String text, GoodsInfoNV.ItemListEntity itemEntity) {
            this.type = type;
            this.text = text;
            this.itemEntity = itemEntity;
        }

        @Override
        public String toString() {
            return text;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeParcelable(this.itemEntity, 0);
            dest.writeInt(this.type);
            dest.writeString(this.text);
            dest.writeInt(this.count);
            dest.writeInt(this.sectionContainCount);
            dest.writeByte(isSelect ? (byte) 1 : (byte) 0);
            dest.writeInt(this.sectionPosition);
            dest.writeInt(this.listPosition);
            dest.writeByte(hasSub ? (byte) 1 : (byte) 0);
            dest.writeTypedList(subList);
        }

        protected GoodsItem(Parcel in) {
            this.itemEntity = in.readParcelable(GoodsInfoNV.ItemListEntity.class.getClassLoader());
            this.type = in.readInt();
            this.text = in.readString();
            this.count = in.readInt();
            this.sectionContainCount = in.readInt();
            this.isSelect = in.readByte() != 0;
            this.sectionPosition = in.readInt();
            this.listPosition = in.readInt();
            this.hasSub = in.readByte() != 0;
            this.subList = in.createTypedArrayList(SubCartBean.CREATOR);
        }

        public static final Creator<GoodsItem> CREATOR = new Creator<GoodsItem>() {
            public GoodsItem createFromParcel(Parcel source) {
                return new GoodsItem(source);
            }

            public GoodsItem[] newArray(int size) {
                return new GoodsItem[size];
            }
        };
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file 'item_goods.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
     */
    static class ViewHolder {
        @InjectView(R.id.goods_img)
        SimpleDraweeView goodsImg;
        @InjectView(R.id.goods_name)
        TextView goodsName;
        @InjectView(R.id.active_info)
        TextView activeInfo;
        @InjectView(R.id.model)
        TextView model;
        @InjectView(R.id.price)
        TextView price;
        @InjectView(R.id.ll_goods_info)
        LinearLayout llGoodsInfo;
        @InjectView(R.id.quantity_controller)
        QuantityController quantityController;
        @InjectView(R.id.sub_layout)
        LinearLayout subLayout;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
}
